package example.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import example.dto.ChildrenInfo;
import example.services.MyTestServices;
import example.untils.HttpClientUtils;
import example.untils.JsonParse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private MyTestServices myTestServices;

    @Autowired
    private JsonParse jsonParse;


    @ResponseBody
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public ModelAndView index() {
        return new ModelAndView("goods");
    }

    @RequestMapping(value = "/groupid={id}",method = RequestMethod.GET)
    public JSONObject getChildInfo(@PathVariable String id) throws IOException {
        String url="https://mobile.yangkeduo.com/goods.html?goods_id="+id;

        String html= HttpClientUtils.doGet(url);

        Document document= Jsoup.parse(html);
        Elements elements_children_scripts=document.getElementsByTag("script");//获取js

        //获取想要JS
        String script;
        String blank;
        String needLogin;
        try{
            script=getScript(elements_children_scripts);
            JSONObject jsonObject1= JSON.parseObject(script);
            blank=jsonObject1.getJSONObject("store").getJSONObject("initDataObj").getString("blank");
            needLogin=jsonObject1.getJSONObject("store").getJSONObject("initDataObj").getString("needLogin");
        }catch (Exception e){
            HashMap<String,Object> map=new HashMap<>();
            map.put("该商品不存在或者需要登录。",0);
            return JSON.parseObject(JSON.toJSONString(map));
        }

        if("true".equals(blank)|| "true".equals(needLogin)){
            HashMap<String,Object> map=new HashMap<>();
            map.put("该商品不存在或者需要登录。",0);
            return JSON.parseObject(JSON.toJSONString(map));
        }else {
            JsonParse.parseJson_children_goods(script);
            List<ChildrenInfo> childrenInfoList=jsonParse.getChildrenInfos();
//            List<String> id_=myTestServices.findChildrenInfo_ID(id);
//            if(id_.size()<=0){
//                int j=myTestServices.insertPhone_Childreninfo(childrenInfoList);
//                System.out.println("插入数据成功.. "+j+" 条");
//            }

//            List<ChildrenInfo> childrenInfoList1=myTestServices.findAll_ChildrenInfo();
            LinkedHashMap<String,Object> map=new LinkedHashMap<>();
            for(ChildrenInfo childrenInfo:childrenInfoList){
                String canshu=childrenInfo.getCh_canshu();
                JSONArray jsonArray= JSON.parseArray(canshu);

                map.put("名称",childrenInfo.getCh_goodsName());
                map.put("pic",JSON.parseArray(childrenInfo.getCh_viewImageUrl()));
                map.put("拼单量",childrenInfo.getCh_sideSalesTip());
                String skus=childrenInfo.getSkus(); //商品样式
                JSONArray jsonArray1= JSON.parseArray(skus);
                JSONObject jsonObject1=new JSONObject();

                JSONArray all_json=new JSONArray();
                for(int j=0;j<jsonArray1.size();j++){
                    JSONObject jsonObject2=new JSONObject();
                    JSONObject o=jsonArray1.getJSONObject(j);
                    jsonObject2.put("imageUrl",o.getString("thumbUrl"));
                    jsonObject2.put("单独购买价格",o.getString("normalPrice"));
                    jsonObject2.put("补贴价格",o.getString("groupPrice"));
                    JSONArray arr=o.getJSONArray("specs");
                    for(int i=0;i<arr.size();i++){
                        jsonObject2.put(arr.getJSONObject(i).getString("spec_key"),arr.getJSONObject(i).getString("spec_value"));
                    }
                    all_json.add(jsonObject2);
                }
                jsonObject1.put("style_arr",all_json);
                map.put("all_styles",jsonObject1);

                JSONArray all_json_guige=new JSONArray();
                JSONObject jj=new JSONObject();
                for(int i=0;i<jsonArray.size();i++){
                    jj.put(jsonArray.getJSONObject(i).getString("key"),
                            jsonArray.getJSONObject(i).getJSONArray("values"));
                }
                all_json_guige.add(jj);
                map.put("规格参数",all_json_guige);
            }
            System.out.println(JSON.toJSONString(map));
            return (JSONObject)JSON.toJSON(map);
        }
    }


    public static String getScript(Elements elements){
        if(elements.size()>0) {
            for (Element element : elements) {
                if (element.childNodes().size() != 0) {
                    if (element.childNodes().get(0).parentNode().toString().contains("window.rawData")) {
                        System.out.println("js的值是 : " + element.childNodes().get(0).parentNode().toString());
                        String jssub = element.childNodes().get(0).parentNode().toString();
                        //截取到想要的json数据
                        String jssub_ = jssub.split("=", 2)[1];
                        String jssub_1 = jssub_.split("<", 2)[0];
                        int fenhao=jssub_1.lastIndexOf(";");
                        String jssub_2 = jssub_1.substring(0,fenhao);
                        System.out.println("最后的json : " + jssub_2);
                        return jssub_2;
                    }
                }
            }
        }
        return null;
    }
}
